<?php

namespace App\Models;

use CodeIgniter\Model;

class Relation_model extends Model
{
    protected $DBGroup = 'default';
    protected $table = 'relationship';
    protected $primaryKey = 'id';
    protected $returnType = 'array';

    protected $allowedFields = ['u_id', 'to_id', 'type'];

    // 构造函数
    public function __construct()
    {
        // 父类 自动使用默认配置组连接数据库
        parent::__construct();
        $this->db = \Config\Database::connect();
    }

    // 新增一条
    public function add_new($u_id, $to_id,$type)
    {
        $builder = $this->db->table($this->table);
        return $builder->insert([
            'u_id' => $u_id,
            'to_id' => $to_id,
            'type' => $type
        ]);
    }

    // 移除一条
    public function delete_old($u_id, $to_id,$type)
    {
        $builder = $this->db->table($this->table);
        return $builder->delete([
            'u_id' => $u_id,
            'to_id' => $to_id,
            'type' => $type
        ]);
    }

    // 检查是否已经关注
    public function check_is_exist($u_id, $to_id,$type)
    {
        $builder = $this->db->table($this->table);
        $builder->where([
                'u_id' => $u_id,
                'to_id' => $to_id,
                'type' => $type
            ]
        );
        $row = $builder->get()->getRowArray();
        if (isset($row)) {
            return $row;
        }
        return false;
    }

    // 拿到关系表
    public function get_list($field, $value, $type, $limit = 10, $offset = 0)
    {
        $builder = $this->db->table($this->table);
        $builder->where([
                $field => $value,
                'type' => $type
            ]
        );
        return $builder->get($limit, $offset)->getResultArray();
    }
}